package com.shareach.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;

import com.benayn.ustyle.logger.Loggers;
import com.shareach.basic.MongoUtilDao;
import com.shareach.domain.common.Entity;
import com.shareach.util.DateUtils;
import com.shareach.util.Globals;
import com.shareach.util.HelperUtil;
import com.shareach.util.JsonUtil;
import com.shareach.util.MD5Util;
import com.shareach.util.PropertiesHolder;
import com.shareach.web.basic.Answer;
import com.shareach.web.basic.Ask;

public class BaseController {
	@Autowired
	protected MongoUtilDao mongoUtilDao;

	protected static final Log log = Loggers.from(BaseController.class);
	protected Short nullShort;
	protected Long nullLong;
	protected Date nullDate;
	protected String nullString;
	protected Integer nullInteger;
	protected Double nullDouble;
	protected int defaultPageSize = 25; // 默认每页记录数
	protected int defaultPageNo = 1; // 默认为第一页

	@Async
	protected void saveCommandAction(String ip, Ask ask, Answer<?> answer) {
		try {
			mongoUtilDao.recordRequestLog(ip,ask, answer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	protected boolean isGet(HttpServletRequest request) {
		return request.getMethod().equals("GET");
	}

	protected boolean isPost(HttpServletRequest request) {
		return request.getMethod().equals("POST");
	}

	protected Integer getPageNo(HttpServletRequest request) {
		Integer pageNo = this.getData(request, "pn", 1);
		if (pageNo < 1) {
			pageNo = 1;
		}
		return pageNo;
	}

	protected Integer getPageSize(HttpServletRequest request) {
		Integer pageSize = this.getData(request, "ps", 1);
		if (pageSize <= 1) {
			pageSize = defaultPageSize;
		}
		return pageSize;
	}

	protected Double getData(HttpServletRequest request, String key, Double defaultValue) {
		String value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		try {
			return Double.parseDouble(request.getParameter(key));
		} catch (Exception exp) {
			return defaultValue;
		}
	}

	protected Short getData(HttpServletRequest request, String key, Short defaultValue) {
		String value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		try {
			return Short.parseShort(request.getParameter(key));
		} catch (Exception exp) {
			return defaultValue;
		}
	}

	protected Integer getData(HttpServletRequest request, String key, Integer defaultValue) {
		String value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		try {
			return Integer.parseInt(request.getParameter(key));
		} catch (Exception exp) {
			return defaultValue;
		}
	}

	protected Date getData(HttpServletRequest request, String key, Date defaultValue) {
		String value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		try {
			return DateUtils.parse(request.getParameter(key));
		} catch (Exception exp) {
			return defaultValue;
		}
	}

	protected Long getData(HttpServletRequest request, String key, Long defaultValue) {
		String value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		try {
			return Long.parseLong(request.getParameter(key));
		} catch (Exception exp) {
			return defaultValue;
		}
	}

	protected String getString(HttpServletRequest request, String key, String defaultValue) {
		return getString(request, key, defaultValue, false);
	}

	protected String getString(HttpServletRequest request, String key, String defaultValue, boolean encode) {
		String value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		try {
			String s = request.getParameter(key);
			if (s != null && encode) {
				s = new String(s.getBytes("utf-8"), "utf-8");
			}
			return s;
		} catch (Exception exp) {
			return defaultValue;
		}
	}

	protected <T> T decodeFromBase64(String input, Class<T> t) throws IOException {
		byte[] bs = HelperUtil.fromBase64(input);
		String json = new String(bs, "utf-8");
		return JsonUtil.objectFromJson(json, t);
	}

	// /**
	// * 保存上传图片
	// * @param request
	// * @param userId
	// * @param files
	// * @return
	// * @throws IOException
	// */
	// public Long[] uploadMultiImage(HttpServletRequest request,long userId)
	// throws IOException{
	// final MultipartHttpServletRequest multiRequest =
	// (MultipartHttpServletRequest) request;
	// final Map<String, MultipartFile> files = multiRequest.getFileMap();
	// ArrayList<Long> fileIds = new ArrayList<Long>();
	// for (Object item : files.values()) {
	// MultipartFile file =
	// (MultipartFile)item;//this.fileAction.addImage(userId, 1, picData);
	// fileIds.add(id);
	// }
	// Long[] result = new Long[fileIds.size()];
	// return fileIds.toArray(result);
	// }
	/**
	 * 保存上传图片
	 * 
	 * @param request
	 * @param userId
	 * @param files
	 * @return
	 * @throws IOException
	 */
	// public Long uploadImage(HttpServletRequest request,long userId) throws
	// IOException{
	// final MultipartHttpServletRequest multiRequest =
	// (MultipartHttpServletRequest) request;
	// final Map<String, MultipartFile> files = multiRequest.getFileMap();
	// Long id = null;
	// for (Object item : files.values()) {
	// MultipartFile file = (MultipartFile)item;
	// byte[] fileData = file.getBytes();
	// id= fileService.addImage(userId, 1L,fileData);
	// }
	// return id;
	// }
	/**
	 * 保存上传图片
	 * 
	 * @param request
	 * @param userId
	 * @param files
	 * @return
	 * @throws IOException
	 */
	// public Long uploadSound(HttpServletRequest request,long userId,int length
	// ) throws IOException{
	// final MultipartHttpServletRequest multiRequest =
	// (MultipartHttpServletRequest) request;
	// final Map<String, MultipartFile> files = multiRequest.getFileMap();
	// Long id = null;
	// for (Object item : files.values()) {
	// MultipartFile file = (MultipartFile)item;
	// byte[] fileData = file.getBytes();
	// id= fileService.addSound(userId,1L, length,fileData);
	// }
	// return id;
	// }

	protected void outText(HttpServletResponse response, String content) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-length", "" + content.getBytes().length);
			PrintWriter pw = response.getWriter();
			pw.write(content);
			pw.flush();
			pw.close();
		} catch (Exception exp) {
			exp.printStackTrace();
			response.setStatus(407);
		}
	}

	protected void outJson(HttpServletResponse response, String content) {
		try {
			response.setHeader("Content-Type", "application/json;charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			// response.setContentType("application/json;charset=UTF-8");
			// response.setCharacterEncoding("UTF-8");

			byte[] bs = content.getBytes("utf-8");
			response.setContentLength(bs.length);
			OutputStream os = response.getOutputStream();
			os.write(bs);

			os.flush();
		} catch (Exception exp) {
			exp.printStackTrace();
			response.setStatus(407);
		}
	}

	@Async
	protected void printLog(Object reqData) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			mapper.writeValue(writer, reqData);
			log.info("[" + DateUtils.parse(new Date(), DateUtils.DATE_TIME_FORMAT) + "]" + writer.toString());
		} catch (Exception exp) {
			exp.printStackTrace();
		}
	}
	protected void addCriteria(Entity domain, Integer val, String propName) {
		if (null == val) {
			return;
		}
		switch (val) {
		case 2:
			domain.addFieldExists(propName);
			break;
		case 3:
			domain.addFieldNoneExists(propName);
			break;
		}
	}
	
	protected String uploadFile(HttpServletRequest request, MultipartFile file, String deployType) {
		String realpath = PropertiesHolder.get(Globals.GLOBAL_IMG_ROOT) + "//" + deployType;
		File desc = new File(realpath);
		if (!desc.exists()) {
			desc.mkdirs();
		}
		File descFile;
		try {
			String orgName = file.getOriginalFilename();
			String type = orgName.substring(orgName.lastIndexOf("."));

			String newFileName = MD5Util.getInputStreamMD5String(file.getInputStream()) + type;
			descFile = new File(realpath + "//" + newFileName);
			file.transferTo(descFile);
			return newFileName;
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		return null;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
	}
}
